﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ScheduleMaker.DB;
using ScheduleMaker.DB.CoreDAO;
using ScheduleMaker.DB.Domain;
using ScheduleMaker.DB.Domain.Core;
using ScheduleMaker.ConfigManager;

namespace ScheduleMaker
{
    public partial class smEmergencyScheduleForm : Form
    {
        const int MAX_NUMBER_OF_SUBJECTS = 50;
        const int columnMinimumWidth = 190;

        IList<DB.Domain.Core.Day> days;
        
        IList<DB.Domain.Core.Group> groups;
        IList<Category> categories;
        IList<DB.Domain.Core.Classroom> classrooms;
        IList<DB.Domain.Core.Teacher> teachers;
        IList<DB.Domain.Core.ClassHour> classHours;
        DateTime weekConstraint;

        Color[] colors;

        Mode mode;

        public smEmergencyScheduleForm()
        {
            InitializeComponent();

            if (ConfigManager.ConfigManager.isConfigLoaded())
            {
                mode = ConfigManager.ConfigManager.getConfiguration().Type;
            }

            if (mode == Mode.School)
            {
                this.Text = "ScheduleMaker - Przeglądanie Planu Awaryjnego - TRYB: SZKOŁA";
            }
            else
            {
                this.labelGroup.Text = "Blok:";
                this.Text = "ScheduleMaker - Przeglądanie Planu Awaryjnego - TRYB: UCZELNIA";
            }

            grid.Rows.Clear();
            grid.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            grid.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            loadDays();
            loadClassHours();
            loadGroupsOrCategories();
            loadTeachers();
            loadClassrooms();

            colors = new Color[] {
                Color.DarkOrange ,
                Color.Yellow ,
                Color.DeepSkyBlue ,
                Color.Violet ,
                Color.LightGreen ,
                Color.Chocolate ,
                Color.DarkGray ,
                Color.LimeGreen ,
                Color.MediumAquamarine ,
                Color.DarkTurquoise ,
                Color.Goldenrod ,
                Color.LightBlue ,
                Color.MediumOrchid ,
                Color.Gold ,
                Color.Tomato ,
                Color.HotPink ,
                Color.Orange ,
                Color.GreenYellow ,
                Color.Magenta ,
                Color.Orchid ,
                Color.RosyBrown ,
                Color.Chartreuse ,
            };

            dtpickWeek.Format  = DateTimePickerFormat.Custom;
            dtpickWeek.CustomFormat = "dd-MM-yyyy HH:mm";

            autoResize();

        }


        private void loadDays()
        {
            // Wczytanie dni tygodnia.
            DayDAO dayDAO = DAOFactory.getDayDAO(mode);
            days = dayDAO.getAll();

            grid.ColumnCount = days.Count;
            int i = 0;
            foreach (var day in days)
            {
                grid.Columns[i].Name = day.Name;
                grid.Columns[i].MinimumWidth = columnMinimumWidth;
                i++;
            }
        }
        private void setWeekConstraint(){
            this.weekConstraint = new DateTime(this.dtpickWeek.Value.Ticks);
        }
        private IList<TeacherUnavailability> getConstraintTeacherUnavailability(IList<TeacherUnavailability> list, DateTime constraintWeek)
        {
            IList<TeacherUnavailability> toReturn = new List<TeacherUnavailability>();
            foreach (var l in list)
            {
                DateTime dt = new DateTime(l.Date);
                if (dt.Year == constraintWeek.Year && theSameWeek(dt, constraintWeek))
                {
                    toReturn.Add(l);
                }
            }
            return toReturn;
        }


        private IList<ClassroomUnavailability> getConstraintClassroomUnavailability(IList<ClassroomUnavailability> list, DateTime constraintWeek)
        {
            IList<ClassroomUnavailability> toReturn = new List<ClassroomUnavailability>();
            foreach (var l in list)
            {
                DateTime dt = new DateTime(l.Date);
                if (dt.Year == constraintWeek.Year && theSameWeek(dt, constraintWeek))
                {
                    toReturn.Add(l);
                }
            }
            return toReturn;
        }

        private IList<EmergencySchedule> getConstraintEmergencySchedule(IList<EmergencySchedule> list, DateTime constraintWeek) {
            IList<EmergencySchedule> toReturn = new List<EmergencySchedule>();
            foreach (var l in list) {
                DateTime dt = new DateTime(l.Date);
                if (dt.Year == constraintWeek.Year && theSameWeek(dt, constraintWeek))
                {
                    toReturn.Add(l);
                }
            }
            return toReturn;
        }
        private void loadClassHours()
        {
            grid.RowHeadersWidth = 200;

            ClassHourDAO classHourDAO = DAOFactory.getClassHourDAO(mode);
            classHours = classHourDAO.getAll();

            int i = 0;
            foreach (var classHour in classHours)
            {
                string[] rowValues = { };
                grid.Rows.Add(rowValues);
                grid.Rows[i++].HeaderCell.Value =
                    classHour.Begin.ToString().Substring(0, 5) +
                    " - " +
                    classHour.End.ToString().Substring(0, 5)
                ;
            }
        }


        private void loadGroupsOrCategories()
        {
            if (mode == Mode.School)
            {
                GroupDAO groupDAO = DAOFactory.getGroupDAO(mode);
                groups = groupDAO.getAll();
                foreach (var elem in groups)
                {
                    comboBoxGroups.Items.Add(elem.Id + " - " + elem.Name);
                }
                comboBoxGroups.DropDownStyle = ComboBoxStyle.DropDownList;
            }
            else
            {
                CategoryDAO categoryDAO = DAOFactory.getCategoryDAO(mode);
                categories = categoryDAO.getAll();
                foreach (var category in categories)
                {
                    comboBoxGroups.Items.Add(category.Id + " - " + category.Name);
                }
                comboBoxGroups.DropDownStyle = ComboBoxStyle.DropDownList;
            }
        }


        private void loadClassrooms()
        {
            ClassroomDAO classroomDAO = DAOFactory.getClassroomDAO(mode);
            classrooms = classroomDAO.getAll();
            foreach (var elem in classrooms)
            {
                comboBoxClassrooms.Items.Add(elem.Id + " - " + elem.Name);
            }
            comboBoxClassrooms.DropDownStyle = ComboBoxStyle.DropDownList;
        }


        private void loadTeachers()
        {
            TeacherDAO teacherDAO = DAOFactory.getTeacherDAO(mode);
            teachers = teacherDAO.getAll();
            foreach (var elem in teachers)
            {
                comboBoxTeachers.Items.Add(elem.Id + " - " + elem.Name);
            }
            comboBoxTeachers.DropDownStyle = ComboBoxStyle.DropDownList;
        }


        private void comboBoxGroups_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (comboBoxGroups.SelectedIndex != -1)
            {
                comboBoxClassrooms.SelectedIndex = -1;
                comboBoxTeachers.SelectedIndex = -1;
            }
        }

        private void comboBoxClassrooms_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (comboBoxClassrooms.SelectedIndex != -1)
            {
                comboBoxGroups.SelectedIndex = -1;
                comboBoxTeachers.SelectedIndex = -1;
            }
        }

        private void comboBoxTeachers_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            if (comboBoxTeachers.SelectedIndex != -1)
            {
                comboBoxGroups.SelectedIndex = -1;
                comboBoxClassrooms.SelectedIndex = -1;
            }
        }


        private void buttonShowPlan_Click_1(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            //setWeekConstraint();
            setWeekConstraint();
            int selectedIndex;
            if ((selectedIndex = comboBoxGroups.SelectedIndex) != -1)
            {
                if (mode == Mode.School)
                {
                    Group group = groups.ElementAt(selectedIndex);
                    loadGroupPlan(group);
                }
                else
                {
                    Category category = categories.ElementAt(selectedIndex);
                    loadCategoryPlan(category);
                }
            }
            else if ((selectedIndex = comboBoxClassrooms.SelectedIndex) != -1)
            {
                Classroom classroom = classrooms.ElementAt(selectedIndex);
                loadClassroomPlan(classroom);
            }
            else if ((selectedIndex = comboBoxTeachers.SelectedIndex) != -1)
            {
                Teacher teacher = teachers.ElementAt(selectedIndex);
                loadTeacherPlan(teacher);
            }

            Cursor = Cursors.Default;
        }


        private void loadGroupPlan(Group g)
        { 
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];

            int[,] subjectsIds = new int[numberOfRows, numberOfColumns];
            int[] subjects = new int[MAX_NUMBER_OF_SUBJECTS];
            int numberOfSubjects = 0;

            //uzupelnienie ScheduleDAO
            ScheduleDAO ScheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = ScheduleDAO.getByGroup(g);
            foreach (var elem in list)
            {
                int currentSubjectId = elem.Subject.Id;
                int position = Array.IndexOf(subjects, currentSubjectId);
                if (position < 0)
                {
                    subjects[numberOfSubjects++] = currentSubjectId;
                }

                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                string cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Classroom.Name;
                cells[rowNumber, columnNumber] = cell;

            }
            //end uzupelnienie ScheduleDAO

            //Podmiana EmergencyScheduleDAO:
            EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            //ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<EmergencySchedule> emergencyList = getConstraintEmergencySchedule(emergencyScheduleDAO.getByGroup(g), this.weekConstraint);
            foreach (var elem in emergencyList)
            {

                int currentSubjectId = elem.Subject.Id;
                int position = Array.IndexOf(subjects, currentSubjectId);
                if (position < 0)
                {
                    subjects[numberOfSubjects++] = currentSubjectId;
                }

                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                string cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Classroom.Name;
                cells[rowNumber, columnNumber] = cell;

            }

            //uzuplenianie 
            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n") {
                        int colorPosition = Array.IndexOf(subjects, subjectsIds[r, b]);
                        grid.Rows[r].Cells[b].Style.BackColor = colors[colorPosition];
                    }
                        //grid.Rows[r].Cells[b].Style.BackColor = Color.LightBlue;
                }
                //
                
            }

            autoResize();
            
        }


        private void loadCategoryPlan(Category category)
        {
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];

            int[,] subjectsIds = new int[numberOfRows, numberOfColumns];
            int[] subjects = new int[MAX_NUMBER_OF_SUBJECTS];
            int numberOfSubjects = 0;

            //ScheduleDAO
            ScheduleDAO ScheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = ScheduleDAO.getAll();
            foreach (var elem in list)
            {
                if (elem.Subject.Category.Id == category.Id)
                {

                    int currentSubjectId = elem.Subject.Id;
                    int position = Array.IndexOf(subjects, currentSubjectId);
                    if (position < 0)
                    {
                        subjects[numberOfSubjects++] = currentSubjectId;
                    }

                    ClassHour classHour = elem.ClassHour;
                    int rowNumber = classHours.IndexOf(classHour);
                    DB.Domain.Core.Day day = elem.Day;
                    int columnNumber = days.IndexOf(day);

                    subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                    string cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                    cells[rowNumber, columnNumber] = cell;

                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                            subjectsIds[rowNumber + time, columnNumber] = currentSubjectId;
                        }
                    }

                }

            }
            //end ScheduleDAO


            //Uzupelnienie EmergencyScheduleDAO
            EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            //ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<EmergencySchedule> emergencyList = getConstraintEmergencySchedule(emergencyScheduleDAO.getAll(), this.weekConstraint);
            foreach (var elem in emergencyList)
            {
                if (elem.Subject.Category.Id == category.Id)
                {

                    int currentSubjectId = elem.Subject.Id;
                    int position = Array.IndexOf(subjects, currentSubjectId);
                    if (position < 0)
                    {
                        subjects[numberOfSubjects++] = currentSubjectId;
                    }

                    ClassHour classHour = elem.ClassHour;
                    int rowNumber = classHours.IndexOf(classHour);
                    DB.Domain.Core.Day day = elem.Day;
                    int columnNumber = days.IndexOf(day);

                    subjectsIds[rowNumber, columnNumber] = currentSubjectId;

                    string cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                    cells[rowNumber, columnNumber] = cell;

                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                            subjectsIds[rowNumber + time, columnNumber] = currentSubjectId;
                        }
                    }

                }

            }
            //end emergencyScheduleDAO

            //uzupelnienie
            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                    {
                        int colorPosition = Array.IndexOf(subjects, subjectsIds[r, b]);
                        grid.Rows[r].Cells[b].Style.BackColor = colors[colorPosition];
                    }
                }
                //

            }

            autoResize();

        }


        private void loadClassroomPlan(Classroom cr)
        { 
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];
            //ScheduleDAO
            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getByClassroom(cr);

            foreach (var elem in list)
            {
                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }

            }
            //end ScheduleDAO

            //ClassroomUnavailability
            ClassroomUnavailabilityDAO classroomUnavailabilityDAO = DAOFactory.getClassroomUnavailabilityDAO(ConfigManager.ConfigManager.getConfiguration().Type);
            IList<ClassroomUnavailability> classroomUnavailability = getConstraintClassroomUnavailability(classroomUnavailabilityDAO.getAll(), this.weekConstraint);

            foreach (var cu in classroomUnavailability)
            {
                if (cu.Classroom.Id == cr.Id)
                {
                    int begin = classHours.IndexOf(cu.Begin);
                    int end = classHours.IndexOf(cu.End);
                    int columnNumber = days.IndexOf(cu.Day);
                    for (int rowNumber = begin; rowNumber <= end; rowNumber++)
                    {
                        cells[rowNumber, columnNumber] = "Niedostepnosc Sali!";
                    }
                }
            }


            //EmergencyScheduleDAO
            EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            IList<EmergencySchedule> emergencyList = getConstraintEmergencySchedule(emergencyScheduleDAO.getByClassroom(cr), this.weekConstraint);

            foreach (var elem in emergencyList)
            {
                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Teacher.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }

            }
            //end EmergencyScheduleDAO

            //uzupelnienie
            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                        grid.Rows[r].Cells[b].Style.BackColor = Color.LightBlue;
                }
                //

            }

            autoResize();
            
        }


        private void loadTeacherPlan(Teacher t)
        { 
            int numberOfRows = classHours.Count;
            int numberOfColumns = days.Count;
            string[,] cells = new string[numberOfRows, numberOfColumns];

            //ScheduleDAO
            ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<Schedule> list = scheduleDAO.getByTeacher(t);

            foreach (var elem in list)
            {
                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }

            }
            //end ScheduleDAO
            //TeacherUnavailability
            TeacherUnavailabilityDAO teacherUnavailabilityDAO = DAOFactory.getTeacherUnavailabilityDAO(ConfigManager.ConfigManager.getConfiguration().Type);
            IList<TeacherUnavailability> teacherUnavailabilities = getConstraintTeacherUnavailability(teacherUnavailabilityDAO.getAll(), this.weekConstraint);

            foreach (var tu in teacherUnavailabilities) {
                if (tu.Teacher.Id == t.Id) {
                    int begin = classHours.IndexOf(tu.Begin);
                    int end = classHours.IndexOf(tu.End);
                    int columnNumber = days.IndexOf(tu.Day);
                    for (int rowNumber = begin; rowNumber <= end; rowNumber++)
                    {
                        cells[rowNumber, columnNumber] = "Niedostepnosc Nauczyciela!";
                    }
                }
            }

            //EmergencyScheduleDAO
            EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            //ScheduleDAO scheduleDAO = DAOFactory.getScheduleDAO(mode);
            IList<EmergencySchedule> emergencyList = getConstraintEmergencySchedule(emergencyScheduleDAO.getByTeacher(t), this.weekConstraint);

            foreach (var elem in emergencyList)
            {
                ClassHour classHour = elem.ClassHour;
                int rowNumber = classHours.IndexOf(classHour);
                DB.Domain.Core.Day day = elem.Day;
                int columnNumber = days.IndexOf(day);

                string cell;
                if (mode == Mode.School)
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name + "\n" + elem.Group.Name;
                }
                else
                {
                    cell = elem.Subject.Name + "\n" + elem.Classroom.Name;
                }
                cells[rowNumber, columnNumber] = cell;

                if (mode == Mode.University)
                {
                    int subjectTime = elem.Subject.Time;
                    if (subjectTime > 1)
                    {
                        for (int time = 1; time < subjectTime; time++)
                        {
                            cells[rowNumber + time, columnNumber] = cell;
                        }
                    }
                }

            }
            //end EmergencyScheduleDAO

            for (int r = 0; r < numberOfRows; r++)
            {
                string[] rowValues = new string[numberOfColumns];
                for (int c = 0; c < numberOfColumns; c++)
                {
                    if (cells[r, c] != null)
                    {
                        rowValues[c] = cells[r, c];
                    }
                    else
                    {
                        rowValues[c] = "\n\n";
                    }
                }
                grid.Rows[r].SetValues(rowValues);

                // na szybko
                int f = grid.ColumnCount;
                for (int b = 0; b < f; b++)
                {
                    grid.Rows[r].Cells[b].Style.BackColor = Color.White;
                }
                for (int b = 0; b < f; b++)
                {
                    if ((grid.Rows[r].Cells[b].Value.ToString()) != "\n\n")
                        grid.Rows[r].Cells[b].Style.BackColor = Color.LightBlue;
                }
                //

            }

            autoResize();

        }

        private void autoResize()
        {
            grid.AutoResizeColumns();
            grid.AutoResizeRows();
            ClientSize = new Size(countGridWidth(), countGridHeight() + 120);

        }

        private int countGridWidth()
        {
            int width = 0;
            foreach (DataGridViewColumn column in grid.Columns)
                if (column.Visible == true)
                    width += column.Width;
            width += grid.RowHeadersWidth;
            width += 50;
            return width;
        }

        private int countGridHeight()
        {
            int height = 0;
            foreach (DataGridViewRow row in grid.Rows)
                if (row.Visible == true)
                    height += row.Height;
            height += grid.ColumnHeadersHeight;
            height += 50;
            return height;
        }
        private DB.Domain.Core.Day getDayID(DateTime dateTime)
        {
            string day = "";
            if (dateTime.DayOfWeek == DayOfWeek.Monday)
            {
                day = "Poniedzialek";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Friday)
            {
                day = "Piatek";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Saturday)
            {
                day = "Sobota";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Sunday)
            {
                day = "Niedziela";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Thursday)
            {
                day = "Czwartek";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Tuesday)
            {
                day = "Wtorek";
            }
            else if (dateTime.DayOfWeek == DayOfWeek.Wednesday)
            {
                day = "Sroda";
            }
            foreach (var d in days)
            {
                if (d.Name.Equals(day))
                {
                    Console.WriteLine("getDayID " + d.Name);
                    return d;
                }
            }
            return null;
        }

        int dayOfWeekToInt(DayOfWeek dayOfWeek)
        {
            if (dayOfWeek == DayOfWeek.Monday)
            {
                return 0;
            }
            else if (dayOfWeek == DayOfWeek.Tuesday)
            {
                return 1;
            }
            else if (dayOfWeek == DayOfWeek.Wednesday)
            {
                return 2;
            }
            else if (dayOfWeek == DayOfWeek.Thursday)
            {
                return 3;
            }
            else if (dayOfWeek == DayOfWeek.Friday)
            {
                return 4;
            }
            else if (dayOfWeek == DayOfWeek.Saturday)
            {
                return 5;
            }
            else if (dayOfWeek == DayOfWeek.Sunday)
            {
                return 6;
            }
            throw new Exception("WTF? Exception");
        }

        bool theSameWeek(DateTime first, DateTime second)
        {

            if (first > second)
            {
                DateTime temp = first;
                first = second;
                second = temp;
            }

            int dayOfWeek = this.dayOfWeekToInt(first.DayOfWeek);
            int daySubstraction = second.DayOfYear - (first.DayOfYear - dayOfWeek);
            if (daySubstraction < 7 && daySubstraction >= 0)
            {
                Console.WriteLine("theSameWeek True: " + first.ToString() + "-" + second.ToString());
                return true;
            }
            return false;
        }

        private void buttonDeleteScheduleWeek_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            this.weekConstraint = dtpickWeek.Value;
            //TeacherUnavailability
            TeacherUnavailabilityDAO teacherUnavailabilityDAO = DAOFactory.getTeacherUnavailabilityDAO(ConfigManager.ConfigManager.getConfiguration().Type);
            IList<TeacherUnavailability> teacherUnavailabilities = getConstraintTeacherUnavailability(teacherUnavailabilityDAO.getAll(), this.weekConstraint);

            //ClassroomUnavailability
            ClassroomUnavailabilityDAO classroomUnavailabilityDAO = DAOFactory.getClassroomUnavailabilityDAO(ConfigManager.ConfigManager.getConfiguration().Type);
            IList<ClassroomUnavailability> classroomUnavailability = getConstraintClassroomUnavailability(classroomUnavailabilityDAO.getAll(), this.weekConstraint);

            //EmergencyScheduleDAO
            EmergencyScheduleDAO emergencyScheduleDAO = DAOFactory.getEmergencyScheduleDAO(mode);
            IList<EmergencySchedule> emergencyList = getConstraintEmergencySchedule(emergencyScheduleDAO.getAll(), this.weekConstraint);

            foreach (var t in teacherUnavailabilities) {
                teacherUnavailabilityDAO.delete(t);
            }
            foreach (var c in classroomUnavailability)
            {
                classroomUnavailabilityDAO.delete(c);
            }
            foreach (var es in emergencyList)
            {
                emergencyScheduleDAO.delete(es);
            }
            Cursor = Cursors.Default;
            MessageBox.Show("Usunieto plan awaryjny dla: " + getWeekStartEndString(this.weekConstraint));
        }

        public String getWeekStartEndString(DateTime date_p)
        {
            DateTime dt = date_p;
            int startOfWeek = dayOfWeekToInt(dt.DayOfWeek);
            long ticksInSecond = TimeSpan.FromSeconds(1).Ticks;
            long ticksInDay = TimeSpan.FromDays(1).Ticks;
            int dayStart = dayOfWeekToInt(dt.DayOfWeek);
            long startTicks = dt.Ticks - dayStart * ticksInDay - dt.Second * ticksInSecond - dt.Minute * 60 * ticksInSecond - dt.Hour * 3600 * ticksInSecond;
            DateTime weekStart = new DateTime(startTicks);
            DateTime weekEnd = new DateTime(startTicks + 7 * ticksInDay - ticksInSecond);
            String st = weekStart.ToString() + " - " + weekEnd.ToString();
            return st;

        }

    }
}
